//
// Copyright (c) 2014, 保留所有权利。
//
// TradeSync.java
//
// 作    者：王红燕
// 当前版本：1.0
// 2014 下午1:15:59
//
// 
//
package com.vanke.agent.sync;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;


import org.apache.log4j.Logger;

import com.vanke.agent.ADataSource;
import com.vanke.agent.C;
import com.vanke.agent.common.CstUtil;

/**
 *公司同步
 */
public class CompanySync extends AgentSync {
	Logger log = Logger.getLogger(CompanySync.class);
	String table = "ek_Company";
	String fields = C.FIELDS_COMPANY;

	@Override
	public void sync() {
		log.info("=============sync new Company===========");
		Connection con = ADataSource.getConnection(ADataSource.SCHEMA_MY);
		Connection wcon = ADataSource.getConnection(ADataSource.SCHEMA_BIZ);

		try {

			String querySql = "SELECT " + fields + "  FROM " + table;
			log.info("execute: " + querySql);
			PreparedStatement pstmt = con.prepareStatement(querySql);
			ResultSet rs = pstmt.executeQuery();
			int count = 0;
			int updateFlag = 0;
			if (!rs.next()) {
				log.info("no Company is created");
				ADataSource.close(rs);
				ADataSource.close(pstmt);
				return;
			}
			
			String insertSql = CstUtil.formatInsertSql(table, fields);
			PreparedStatement wpstmt = wcon.prepareStatement(insertSql);
			int columns = fields.split(",").length;
			
			String updateSql = CstUtil.formatUpdateSql(table, fields);
			updateSql += " where BUGUID =?";
			log.info("execute update : " + updateSql);
			PreparedStatement dataUpdatePs = wcon.prepareStatement(updateSql);
			
			PreparedStatement dataps = wcon.prepareStatement(querySql);
			ResultSet datars = dataps.executeQuery();
			Map<String,Boolean> dataGuidMap = new HashMap<String,Boolean>();
			while(datars.next()){
				dataGuidMap.put(datars.getString("BUGUID").trim(), true);
			}
			
			do{
				try {
					for (int i = 1; i <= columns; i++) {
						wpstmt.setString(i, rs.getString(i));
						dataUpdatePs.setString(i, rs.getString(i));
					}
					/**存在该记录就更新否则插入**/
					if(dataGuidMap.containsKey(rs.getString("BUGUID").trim())){
						dataUpdatePs.setString(3,rs.getString("BUGUID"));
						dataUpdatePs.executeUpdate();
						updateFlag++;
					}else{
						wpstmt.executeUpdate();
						count++;
					}
				} catch (Exception e) {
					e.printStackTrace();
					log.error(e);
				}

				// TODO 通知消息

			}while (rs.next());
			
			// 关闭
			ADataSource.close(rs);
			ADataSource.close(datars);
			ADataSource.close(pstmt);
			ADataSource.close(wpstmt);
			ADataSource.close(dataUpdatePs);
			ADataSource.close(dataps);

			log.info(count + " Companys save ");
			log.info(updateFlag + " Companys update ");
			log.info("=============sync Company end===========");

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			ADataSource.close(con);
			ADataSource.close(wcon);
		}
	} // ~sync
}
